package cn.lisens.config;

import javax.sql.DataSource;

import org.flowable.engine.HistoryService;
import org.flowable.engine.ManagementService;
import org.flowable.engine.ProcessEngine;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.spring.ProcessEngineFactoryBean;
import org.flowable.spring.SpringProcessEngineConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.orm.hibernate5.HibernateTransactionManager;

@Configuration
public class FlowableConfig {
	
	@Autowired
	private ProcessEngine processEngine;
	
	private final Resource[] deploymentResources;
	public FlowableConfig(@Value("classpath*:/processes/*.bpmn20.xml") Resource[] templates) {
		this.deploymentResources = templates;
	}
	
	@Bean
	public SpringProcessEngineConfiguration processEngineConfiguration(DataSource dataSource,HibernateTransactionManager transactionManager) {
		SpringProcessEngineConfiguration config = new SpringProcessEngineConfiguration();
		config.setDataSource(dataSource);
		config.setTransactionManager(transactionManager);
		config.setDatabaseSchemaUpdate(SpringProcessEngineConfiguration.DB_SCHEMA_UPDATE_TRUE);
		config.setAsyncExecutorActivate(false);
		config.setDeploymentResources(deploymentResources);
		return config;
	}
	
	@Bean
	public ProcessEngineFactoryBean processEngine(SpringProcessEngineConfiguration processEngineConfiguration) {
		ProcessEngineFactoryBean p = new ProcessEngineFactoryBean();
		p.setProcessEngineConfiguration(processEngineConfiguration);
		return p;
	}
	
	@Bean
	public RepositoryService repositoryService() {
		return processEngine.getRepositoryService();
	}
	
	@Bean
	public RuntimeService runtimeService() {
		return processEngine.getRuntimeService();
	}
	
	@Bean
	public TaskService taskService() {
		return processEngine.getTaskService();
	}

	@Bean
	public HistoryService historyService() {
		return processEngine.getHistoryService();
	}

	@Bean
	public ManagementService managementService() {
		return processEngine.getManagementService();
	}

}
